{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n",
        "[Learn the Basics](intro.html) ||\n",
        "[Quickstart](quickstart_tutorial.html) ||\n",
        "[Tensors](tensorqs_tutorial.html) ||\n",
        "**Datasets & DataLoaders** ||\n",
        "[Transforms](transforms_tutorial.html) ||\n",
        "[Build Model](buildmodel_tutorial.html) ||\n",
        "[Autograd](autogradqs_tutorial.html) ||\n",
        "[Optimization](optimization_tutorial.html) ||\n",
        "[Save & Load Model](saveloadrun_tutorial.html)\n",
        "\n",
        "# Datasets & DataLoaders\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Code for processing data samples can get messy(混乱) and hard to maintain; we ideally want our dataset code\n",
        "to be decoupled(解耦) from our model training code for better readability and modularity.\n",
        "PyTorch provides two data primitives: ``torch.utils.data.DataLoader`` and ``torch.utils.data.Dataset``\n",
        "that allow you to use pre-loaded datasets as well as your own data.\n",
        "``Dataset`` stores the samples and their corresponding labels, and ``DataLoader`` wraps an iterable around\n",
        "the ``Dataset`` to enable easy access to the samples.\n",
        "\n",
        "PyTorch domain libraries provide a number of pre-loaded datasets (such as FashionMNIST) that\n",
        "subclass ``torch.utils.data.Dataset`` and implement functions specific to the particular data.\n",
        "They can be used to prototype and benchmark your model. You can find them\n",
        "here: [Image Datasets](https://pytorch.org/vision/stable/datasets.html),\n",
        "[Text Datasets](https://pytorch.org/text/stable/datasets.html), and\n",
        "[Audio Datasets](https://pytorch.org/audio/stable/datasets.html)\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Loading a Dataset\n",
        "\n",
        "Here is an example of how to load the [Fashion-MNIST](https://research.zalando.com/project/fashion_mnist/fashion_mnist/) dataset from TorchVision.\n",
        "Fashion-MNIST is a dataset of Zalando’s article images consisting of 60,000 training examples and 10,000 test examples.\n",
        "Each example comprises a 28×28 grayscale image and an associated label from one of 10 classes.\n",
        "\n",
        "We load the [FashionMNIST Dataset](https://pytorch.org/vision/stable/datasets.html#fashion-mnist) with the following parameters:\n",
        " - ``root`` is the path where the train/test data is stored,\n",
        " - ``train`` specifies training or test dataset,\n",
        " - ``download=True`` downloads the data from the internet if it's not available at ``root``.\n",
        " - ``transform`` and ``target_transform`` specify the feature and label transformations\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import torch\n",
        "from torch.utils.data import Dataset\n",
        "from torchvision import datasets\n",
        "from torchvision.transforms import ToTensor\n",
        "import matplotlib.pyplot as plt\n",
        "\n",
        "ROOT = \"E:/sfxData/DeepLearning\"\n",
        "\n",
        "# 60000, [1,28,28]\n",
        "training_data = datasets.FashionMNIST(\n",
        "    root=ROOT,\n",
        "    train=True,\n",
        "    download=True,\n",
        "    transform=ToTensor()\n",
        ")\n",
        "\n",
        "# 10000\n",
        "test_data = datasets.FashionMNIST(\n",
        "    root=ROOT,\n",
        "    train=False,\n",
        "    download=True,\n",
        "    transform=ToTensor()\n",
        ")\n",
        "\n",
        "print(training_data)\n",
        "print(test_data)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Iterating and Visualizing the Dataset\n",
        "\n",
        "We can index ``Datasets`` manually like a list: ``training_data[index]``.\n",
        "We use ``matplotlib`` to visualize some samples in our training data.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# 标签\n",
        "labels_map = {\n",
        "    0: \"T-Shirt\",\n",
        "    1: \"Trouser\",\n",
        "    2: \"Pullover\",\n",
        "    3: \"Dress\",\n",
        "    4: \"Coat\",\n",
        "    5: \"Sandal\",\n",
        "    6: \"Shirt\",\n",
        "    7: \"Sneaker\",\n",
        "    8: \"Bag\",\n",
        "    9: \"Ankle Boot\",\n",
        "}\n",
        "figure = plt.figure(figsize=(8, 8))\n",
        "cols, rows = 3, 3\n",
        "for i in range(1, cols * rows + 1): # 1 to 10\n",
        "    sample_idx = torch.randint(len(training_data), size=(1,)).item()\n",
        "    img, label = training_data[sample_idx]\n",
        "    figure.add_subplot(rows, cols, i)\n",
        "    plt.title(labels_map[label])\n",
        "    plt.axis(\"off\")\n",
        "    plt.imshow(img.squeeze(), cmap=\"gray\")\n",
        "plt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "..\n",
        " .. figure:: /_static/img/basics/fashion_mnist.png\n",
        "   :alt: fashion_mnist\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "--------------\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Creating a Custom Dataset for your files\n",
        "\n",
        "A custom Dataset class must implement three functions: `__init__`, `__len__`, and `__getitem__`.\n",
        "Take a look at this implementation; the FashionMNIST images are stored\n",
        "in a directory ``img_dir``, and their labels are stored separately in a CSV file ``annotations_file``.\n",
        "\n",
        "In the next sections, we'll break down what's happening in each of these functions.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import os\n",
        "import pandas as pd\n",
        "from torchvision.io import read_image\n",
        "\n",
        "class CustomImageDataset(Dataset):\n",
        "    def __init__(self, annotations_file, img_dir, transform=None, target_transform=None):\n",
        "        self.img_labels = pd.read_csv(annotations_file)\n",
        "        self.img_dir = img_dir\n",
        "        self.transform = transform\n",
        "        self.target_transform = target_transform\n",
        "\n",
        "    def __len__(self):\n",
        "        return len(self.img_labels)\n",
        "\n",
        "    def __getitem__(self, idx):\n",
        "        img_path = os.path.join(self.img_dir, self.img_labels.iloc[idx, 0])\n",
        "        image = read_image(img_path)\n",
        "        label = self.img_labels.iloc[idx, 1]\n",
        "        if self.transform:\n",
        "            image = self.transform(image)\n",
        "        if self.target_transform:\n",
        "            label = self.target_transform(label)\n",
        "        return image, label"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### __init__\n",
        "\n",
        "The __init__ function is run once when instantiating the Dataset object. We initialize\n",
        "the directory containing the images, the annotations file, and both transforms (covered\n",
        "in more detail in the next section).\n",
        "\n",
        "The labels.csv file looks like: ::\n",
        "\n",
        "    tshirt1.jpg, 0\n",
        "    tshirt2.jpg, 0\n",
        "    ......\n",
        "    ankleboot999.jpg, 9\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "def __init__(self, annotations_file, img_dir, transform=None, target_transform=None):\n",
        "    self.img_labels = pd.read_csv(annotations_file)\n",
        "    self.img_dir = img_dir\n",
        "    self.transform = transform\n",
        "    self.target_transform = target_transform"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### __len__\n",
        "\n",
        "The __len__ function returns the number of samples in our dataset.\n",
        "\n",
        "Example:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "def __len__(self):\n",
        "    return len(self.img_labels)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### __getitem__\n",
        "\n",
        "The __getitem__ function loads and returns a sample from the dataset at the given index ``idx``.\n",
        "Based on the index, it identifies the image's location on disk, converts that to a tensor using ``read_image``, retrieves the\n",
        "corresponding label from the csv data in ``self.img_labels``, calls the transform functions on them (if applicable), and returns the\n",
        "tensor image and corresponding label in a tuple.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "def __getitem__(self, idx):\n",
        "    img_path = os.path.join(self.img_dir, self.img_labels.iloc[idx, 0])\n",
        "    image = read_image(img_path)\n",
        "    label = self.img_labels.iloc[idx, 1]\n",
        "    if self.transform:\n",
        "        image = self.transform(image)\n",
        "    if self.target_transform:\n",
        "        label = self.target_transform(label)\n",
        "    return image, label"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "--------------\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Preparing your data for training with DataLoaders\n",
        "The ``Dataset`` retrieves our dataset's features and labels one sample at a time. While training a model, we typically want to\n",
        "pass samples in \"minibatches\", reshuffle the data at every epoch to reduce model overfitting, and use Python's ``multiprocessing`` to\n",
        "speed up data retrieval.\n",
        "\n",
        "``DataLoader`` is an iterable that abstracts this complexity for us in an easy API.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from torch.utils.data import DataLoader\n",
        "\n",
        "train_dataloader = DataLoader(training_data, batch_size=64, shuffle=True)\n",
        "test_dataloader = DataLoader(test_data, batch_size=64, shuffle=True)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Iterate through the DataLoader\n",
        "\n",
        "We have loaded that dataset into the ``DataLoader`` and can iterate through the dataset as needed.\n",
        "Each iteration below returns a batch of ``train_features`` and ``train_labels`` (containing ``batch_size=64`` features and labels respectively).\n",
        "Because we specified ``shuffle=True``, after we iterate over all batches the data is shuffled (for finer-grained control over\n",
        "the data loading order, take a look at [Samplers](https://pytorch.org/docs/stable/data.html#data-loading-order-and-sampler)).\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# Display image and label.\n",
        "train_features, train_labels = next(iter(train_dataloader))\n",
        "print(f\"Feature batch shape: {train_features.size()}\")\n",
        "print(f\"Labels batch shape: {train_labels.size()}\")\n",
        "img = train_features[0].squeeze()\n",
        "label = train_labels[0]\n",
        "plt.imshow(img, cmap=\"gray\")\n",
        "plt.show()\n",
        "print(f\"Label: {label}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "--------------\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Further Reading\n",
        "- [torch.utils.data API](https://pytorch.org/docs/stable/data.html)\n",
        "\n"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.9.9 (tags/v3.9.9:ccb0e6a, Nov 15 2021, 18:08:50) [MSC v.1929 64 bit (AMD64)]"
    },
    "vscode": {
      "interpreter": {
        "hash": "cf18841ace8313d0bc088ca146c17a6c0040e82121d5cb75c0ea07172309253d"
      }
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
